import Vue from 'vue'
import VueRouter from 'vue-router'
import Course from '@/views/course'
import store from '@/store'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Course',
    component: Course
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import(/* webpackChunkName: "Login" */ '../views/login')
  },
  {
    path: '/learn',
    name: 'Learn',
    component: () => import(/* webpackChunkName: "Learn" */ '../views/learn'),
    meta: { requiresAuth: true }
  },
  {
    path: '/user',
    name: 'User',
    component: () => import(/* webpackChunkName: "User" */ '../views/user'),
    meta: { requiresAuth: true }
  },
  {
    path: '/course-info/:courseId',
    name: 'CourseInfo',
    component: () => import(/* webpackChunkName: "course-ingo" */ '../views/course-info'),
    props: true
  },
  {
    path: '/course-video/:lessonId',
    name: 'CourseVideo',
    component: () => import(/* webpackChunkName: "course-video" */ '../views/course-info/video'),
    props: true
  },
  {
    path: '/pay/:courseId',
    name: 'pay',
    component: () => import(/* webpackChunkName: "pay" */ '../views/pay'),
    props: true
  },
  {
    path: '*',
    name: 'error-page',
    component: () => import(/* webpackChunkName: "error-page" */ '../views/error-page')
  }
]

const router = new VueRouter({
  routes
})
// 设置导航守卫
router.beforeEach((to, from, next) => {
  // 是否需要进行身份验证
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!store.state.user) {
      return next({ name: 'Login', query: { directe: to.fullPath } })
    }
    next()
  } else {
    next()
  }
})
export default router
